import canEditTable from '../Components/canEditTable.vue';
import tableData from './permissions-data.js';
import validate from '../../libs/validate';

export default {
    // name:'permissions-index',
    components: {
        canEditTable
    },
    computed: {
        menuList() {
            return this.$store.state.app.menuList;
        },
    },
    data() {
        return {
            user: '',
            treeArr: [],
            rolesColumns: [],
            rolesData: [],
            initRoleData: [],
            usersColumns: [],
            usersData: [],
            initUsersData: [],
            selectRole: '',
            selectChanged: false,
            selectChangedArr: [],
            showAddModal: false,
            permissionsNotChange: true,
            showAddModalLoading: true,
            addType: '', //role or users
            addRoleModalRules: {
                name: [{
                    required: true,
                    validator: validate.name,
                    trigger: 'blur'
                }],
            },
            addRoleModalForm: {
                name: '',
                isAutoAllocation: true
            },
            addUsersModalRules: {
                name: [{
                    required: true,
                    validator: validate.name,
                    trigger: 'blur'
                }],
                mail: [{
                    required: false,
                    type: 'email',
                    message: '请输入正确的email',
                    trigger: 'blur'
                }],
                password: [{
                        required: true,
                        validator: validate.password,
                        trigger: 'blur'
                    }

                ],
                tel: [{
                    required: false,
                    validator: validate.tel,
                    trigger: 'blur'

                }],
                roles: [{
                    required: true,
                    message: '请分配角色',
                    trigger: 'change'
                }]
            },
            addUsersModalForm: {
                name: '',
                password: '',
                roles: '',
                mail: '',
                tel: ''
            }
        }
    },
    methods: {
        rowClick(currentRow) {
            if (!(currentRow && this.selectRole && currentRow.role == this.selectRole.role)) {
                this.selectRole = currentRow;
                this.queryTree()
            }

        },
        initRolesList() {
            this.http.post(this.postUrl.getRolesList, {
                token: this.user.tokenList[0]
            }).then((data) => {
                console.log(data);
                if (data.code >= 0) {
                    this.initRoleData = data.data;
                    let rolelist = []
                    for (let i = 0; i < data.data.length; i++) {
                        if (!data.data[i].is_supper_admin) {
                            rolelist.push({
                                uuid: data.data[i].uuid,
                                role: data.data[i].role,
                                label: data.data[i].role,
                            })
                        }
                    }
                    this.rolesData = rolelist;
                } else {
                    this.errorHandle(data.msg)
                }
            }, () => {
                this.errorHandle()
            }).then(() => {
                this.initUserList()

            })
        },
        initUserList() {
            this.http.post(this.postUrl.getUsersList, {
                token: this.user.tokenList[0]
            }).then((data) => {
                console.log(data);
                if (data.code > -1) {
                    let usersList = []
                    this.initUsersData = data.data;
                    for (let i = 0; i < data.data.length; i++) {
                        if (!data.data[i].is_supper_admin) {
                            usersList.push({
                                name: data.data[i].name,
                                select: data.data[i].role_uuid,
                                options: this.rolesData,
                                uuid: data.data[i].uuid,
                                password: '*'
                            })
                        }
                    }
                    this.usersData = usersList;
                    console.log(this.usersData);
                } else {
                    this.errorHandle(data.msg)

                }
            })
        },
        queryTree() {
            let rolePermissions = []
            for (let i = 0; i < this.initRoleData.length; i++) {
                if (this.selectRole.uuid == this.initRoleData[i].uuid) {
                    rolePermissions = JSON.parse(this.initRoleData[i].role_info)
                    this.selectRole.rolePermissions = rolePermissions;
                }
            }
            this.initTree(false)
            // let rolePermissions = [{
            //     name: 'file-upload',
            //     title: '文件上传'

            // }, {
            //     name: 'file-upload',
            //     title: '文本框'
            // }]
            this.treeArr.forEach((item) => {
                for (let i = 0; i < rolePermissions.length; i++) {
                    if (item.children && item.children.length > 0) {
                        for (let j = 0; j < item.children.length; j++) {
                            if (rolePermissions[i] == item.children[j].name) {
                                this.$set(item.children[j], 'checked', true)
                            }
                        }
                    } else {
                        if (rolePermissions[i] == item.name) {
                            this.$set(item, 'checked', true)
                        }
                    }
                }
            });
        },
        initTree(cantEdit) {
            if (cantEdit === undefined) {
                cantEdit = true
            }
            let treeArr = [];
            let menuList = JSON.parse(JSON.stringify(this.menuList));
            console.log(menuList);
            menuList.forEach((item) => {
                if (item.access === 0) {
                    return
                }
                item.expand = true;
                //如果有children并且大于1.则为二级菜单
                if (item.children.length > 1) {
                    if (item.component) {
                        delete item.component
                    }
                    this.$set(item, 'disabled', cantEdit);
                    this.$set(item, 'checked', cantEdit);
                    this.$set(item, 'disableCheckbox', cantEdit);
                    for (let i = 0; i < item.children.length; i++) {
                        this.$set(item.children[i], 'disabled', cantEdit);
                        this.$set(item.children[i], 'checked', cantEdit);
                        this.$set(item.children[i], 'disableCheckbox', cantEdit);
                        if (item.children[i].component) {
                            delete item.children[i].component
                        }
                    }

                    treeArr.push(item)
                } else {
                    //如果有children并且等于1.则为一级菜单
                    this.$set(item.children[0], 'disabled', cantEdit);
                    this.$set(item.children[0], 'checked', cantEdit);
                    this.$set(item.children[0], 'disableCheckbox', cantEdit);
                    if (item.children[0].component) {
                        delete item.children[0].component
                    }
                    treeArr.push(item.children[0])
                }
            });
            this.treeArr = treeArr;
        },
        /**
         *
         * 把树状图转换成所有子节点的数组合集
         * @returns {Array}
         *
         */
        treeToArr() {
            let roles = [];
            this.treeArr.forEach(item => {
                if (item.children && item.children.length === 1) {
                    roles.push(item.children[0].name)
                } else if (item.children && item.children.length > 1) {
                    for (let i = 0; i < item.children.length; i++) {
                        roles.push(item.children[i].name)
                    }
                } else {
                    roles.push(item.name)
                }
            });
            console.log(roles);
            return roles;
        },
        addRole() {
            // console.log(this.addRoleModalForm);
            // return
            this.$refs.addRoleModalForm.validate((valid) => {
                console.log(valid);
                if (valid) {
                    this.$nextTick(() => {
                        this.showAddModalLoading = true;
                    })
                    let roles = this.treeToArr();
                    this.http.post(this.postUrl.addRoleMenbers, {
                        roleName: this.addRoleModalForm.name,
                        token: this.user.tokenList[0],
                        roleInfo: this.addRoleModalForm.isAutoAllocation ? JSON.stringify(roles) : '[]'
                    }).then((data) => {
                        if (data.code >= 0) {
                            this.initRolesList();
                            this.showAddModal = false;
                            this.addRoleModalForm = {
                                name: '',
                                isAutoAllocation: true
                            }
                        } else {
                            this.errorHandle(data.msg)
                        }
                    }, () => {
                        this.errorHandle()
                    }).then(() => {
                        this.showAddModalLoading = true;
                    })
                } else {
                    this.showAddModalLoading = false;
                    this.$nextTick(() => {
                        this.showAddModalLoading = true;
                    });
                }
            })
        },
        addUsers() {
            this.$refs.addUsersModalForm.validate((valid) => {
                if (valid) {
                    this.$nextTick(() => {
                        this.showAddModalLoading = true;
                    })
                    this.http.post(this.postUrl.addUsersMenbers, {
                        token: this.user.tokenList[0],
                        name: this.addUsersModalForm.name,
                        pwd: this.addUsersModalForm.password,
                        email: this.addUsersModalForm.mail,
                        tel: this.addUsersModalForm.tel,
                        role_uuid: this.addUsersModalForm.roles,
                        icon: ('http://bl-img.oss-cn-shenzhen.aliyuncs.com/system_headimg/system_headimg_20171201.jpg')
                    }).then((data) => {
                        if (data.code > -1) {
                            this.showAddModal = false;
                            this.usersData.push({
                                name: data.data.name,
                                select: data.data.role_uuid,
                                options: this.rolesData,
                                uuid: data.data.uuid
                            })
                            this.addUsersModalForm = {
                                name: '',
                                password: '',
                                roles: '',
                                mail: '',
                                tel: ''
                            }
                        } else {
                            this.errorHandle(data.msg)
                        }
                    }, () => {
                        this.showAddModalLoading = false;
                        this.$nextTick(() => {
                            this.showAddModalLoading = true;
                        });
                    })
                } else {
                    this.showAddModalLoading = false;
                    this.$nextTick(() => {
                        this.showAddModalLoading = true;
                    });
                }
            })

        },
        modalOk(type) {
            if (type == 'role') {
                this.addRole()
            } else {
                this.addUsers()

            }
        },
        showModal(type) {
            this.addType = type;
            this.showAddModal = true;
        },
        deleteRole(val, index) {
            let onDeleteRole = this.rolesData[index];
            console.log(this.rolesData[index]);
            this.http.post(this.postUrl.deleteRole, {
                roleUuid: this.rolesData[index].uuid,
                token: this.user.tokenList[0]
            }).then((data) => {
                if (data.code >= 0) {
                    this.$Notice.success({
                        title: '删除成功！',
                    });
                    this.initRolesList();
                    this.selectRole = '';
                    this.initTree(true);
                } else {
                    this.errorHandle(data.msg)
                    this.rolesData.splice(index, 0, onDeleteRole)
                }
            }, () => {
                this.rolesData.splice(index, 0, onDeleteRole)
                this.errorHandle()
            })
        },
        deleteUser(val, index) {
            let onDeleteUsers = this.usersData[index];
            console.log({
                token: this.user.tokenList[0],
                user_uuid: this.usersData[index].uuid,
            });
            this.http.post(this.postUrl.deleteUser, {
                token: this.user.tokenList[0],
                user_uuid: this.usersData[index].uuid,
            }).then((data) => {
                if (data.code >= 0) {
                    this.$Notice.success({
                        title: '删除成功！',
                    });
                    this.initUserList()
                } else {
                    this.errorHandle(data.msg)
                    this.usersData.splice(index, 0, onDeleteUsers)
                }
            },()=>{
                this.errorHandle()
                this.usersData.splice(index, 0, onDeleteUsers)
            })
        },
        handleChangeUser(val, index) {
            let oldData = '';
            let changeData = {};
            for (let i = 0; i < this.initUsersData.length; i++) {
                if (this.initUsersData[i].uuid === val[index].uuid) {
                    oldData = {
                        name: this.initUsersData[i].name,
                        select: this.initUsersData[i].role_uuid,
                        options: this.rolesData,
                        uuid: this.initUsersData[i].uuid,
                        password: '*'
                    }
                    changeData = {
                        role_uuid: val[index].select,
                        user_uuid: val[index].uuid,
                        token: this.user.tokenList[0],
                        new_password: val[index].password
                    }
                    break
                }
            }
            if(oldData.select == changeData.role_uuid && oldData.password == changeData.new_password ){
                this.$Message.warning('未作出修改');
                return
            }
            this.http.post(this.postUrl.changeUsersInfo, changeData).then((data) => {
                if (data.code > -1) {
                    this.$Notice.success({
                        title: '修改成功',
                    });
                    this.initUserList();
                } else {
                    this.errorHandle(data.msg);
                    this.rolesData.splice(index, 0, oldData)
                }
            }, () => {
                this.errorHandle();
            })
        },
        handleChangeRole(val, index) {
            console.log(val, index);
            let oldData = '';
            let changeData = {};
            for (let i = 0; i < this.initRoleData.length; i++) {
                if (this.initRoleData[i].uuid === val[index].uuid) {
                    oldData = {
                        uuid: this.initRoleData[i].uuid,
                        role: this.initRoleData[i].role,
                        label: this.initRoleData[i].role,
                    }
                    changeData = {
                        roleUuid: val[index].uuid,
                        roleName: val[index].role,
                        roleInfo: this.initRoleData[i].role_info,
                        token: this.user.tokenList[0]
                    }
                    break
                }
            }
            if(oldData.role === changeData.roleName){
                this.$Message.warning('未作出修改');
                return
            }
            this.http.post(this.postUrl.changeRoleInfo, changeData).then((data) => {
                if (data.code > -1) {
                    this.$Notice.success({
                        title: '修改成功',
                    });
                    this.initRolesList()
                } else {
                    this.errorHandle(data.msg);
                    this.rolesData.splice(index, 0, oldData)
                }
            }, () => {
                this.errorHandle();
            })

        },
        treeCheckChange(items) {
            let checkedArr = [];
            console.log(this.selectRole);

            items.forEach(item => {
                if (!item.children) {
                    checkedArr.push(item.name)
                }
            });
            this.permissionsNotChange = (JSON.stringify(checkedArr.sort()) == JSON.stringify(this.selectRole.rolePermissions.sort()))
        },
        savePermissions() {
            let treeChecked = this.$refs.roleTree.getCheckedNodes();
            let checkedArr = [];

            treeChecked.forEach(item => {
                if (!item.children) {
                    checkedArr.push(item.name)
                }
            });
            this.http.post(this.postUrl.changeRoleInfo, {
                roleUuid: this.selectRole.uuid,
                roleName: this.selectRole.role,
                roleInfo: JSON.stringify(checkedArr),
                token: this.user.tokenList[0]
            }).then((data) => {
                if (data.code > -1) {
                    this.initRolesList();
                    this.$Notice.success({
                        title: '修改成功！',
                    });
                } else {
                    this.errorHandle(data.msg)
                }
                this.permissionsNotChange = true;
            }, () => {
                this.errorHandle()
            })
        }
    },
    created() {
        this.rolesColumns = tableData.editInlineColumns;
        // this.rolesData = tableData.editInlineData;
        this.usersColumns = tableData.usersColumns;
        // this.usersData = tableData.usersData;
        this.selectChangedArr = this.rolesData;
        if (this.menuList.length) {
            this.initTree()
        } else {
            setTimeout(() => {
                this.initTree()
            }, 200);
        }
        if (!this.user) {
            this.storage.get('user').then((user) => {
                this.user = user
                this.initRolesList()
            })
        } else {
            this.initRolesList()
        }
    }
}
